<template>
  <div class="note-detail-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="header-left">
            <el-button @click="$router.push('/notes')" icon="ArrowLeft" class="back-btn">
              返回
            </el-button>
          </div>
          <div class="header-center">
            <div class="page-title">
              <el-icon class="title-icon"><Document /></el-icon>
              <h2>笔记</h2>
            </div>
          </div>
          <div class="header-right">
            <div class="current-time">
              <div class="time-info">
                <!-- <span class="time-text"></span> -->
                <span class="date-text">{{ currentDate }} {{ currentTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-header>
      
      <el-main class="main">
        <el-card class="note-card" @dblclick="handleContainerDoubleClick">
          <template #header>
            <div class="note-header">
              <h3>{{ noteTitle || '无标题' }}</h3>
              <div class="note-status">
                <el-tag v-if="isEditing" type="warning">编辑模式</el-tag>
                <el-tag v-else type="info">只读模式</el-tag>
                <span v-if="lastUpdateTime" class="update-time">
                  {{ lastUpdateTime }}
                </span>
              </div>
            </div>
          </template>
          
          <div class="note-content">
            <el-input
              v-model="noteContent"
              type="textarea"
              placeholder="双击开始编辑笔记..."
              :readonly="!isEditing"
              @dblclick.stop="startEditing"
              resize="none"
              class="note-textarea"
              ref="noteTextarea"
              @click.stop
              @input="adjustTextareaHeight"   
            />
          </div>
          
          <div class="note-footer">
            <div class="edit-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>双击文本框进入编辑模式，双击其他地方自动保存</span>
            </div>
            <div class="note-description">
              <el-icon><Edit /></el-icon>
              <span>这里记录您的笔记内容，是您思想的专属空间</span>
            </div>
          </div>
        </el-card>
      </el-main>
    </el-container>
    

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { InfoFilled, Edit, Document } from '@element-plus/icons-vue'


const route = useRoute()
const router = useRouter()
const note = ref({})
const noteContent = ref('')
const isEditing = ref(false)
const saving = ref(false)
const lastUpdateTime = ref('')
const noteTextarea = ref(null)

const noteTitle = computed(() => {
  // 获取第一行内容，若不存在则用'无标题'
  const firstLine = note.value?.content?.split('\n')[0] || '无标题';
  // 截取前5个字符
  return firstLine.length > 5 ? firstLine.slice(0, 5) : firstLine;
});

const currentTime = computed(() => {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
});

const currentDate = computed(() => {
  const now = new Date();
  const month = (now.getMonth() + 1).toString();
  const day = now.getDate().toString();
  return `${month}月${day}日`;
});

const noteGroup = computed(() => {
  return note.value?.group_name || null
})

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const noteTime = new Date(timestamp)
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
  
  if (noteTime >= today) {
    return `今天 ${noteTime.getHours().toString().padStart(2, '0')}:${noteTime.getMinutes().toString().padStart(2, '0')}`
  } else if (noteTime >= yesterday) {
    return `昨天 ${noteTime.getHours().toString().padStart(2, '0')}:${noteTime.getMinutes().toString().padStart(2, '0')}`
  } else {
    return `${noteTime.getFullYear()}-${(noteTime.getMonth() + 1).toString().padStart(2, '0')}-${noteTime.getDate().toString().padStart(2, '0')} ${noteTime.getHours().toString().padStart(2, '0')}:${noteTime.getMinutes().toString().padStart(2, '0')}`
  }
}

const formatUpdateTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const updateTime = new Date(timestamp)
  const timeDifference = Math.floor((now - updateTime) / 1000)
  
  if (timeDifference < 60) {
    return `${timeDifference} 秒前`
  } else if (timeDifference < 3600) {
    return `${Math.floor(timeDifference / 60)} 分钟前`
  } else if (timeDifference < 86400) {
    return `${Math.floor(timeDifference / 3600)} 小时前`
  } else if (timeDifference < 2592000) {
    return `${Math.floor(timeDifference / 86400)} 天前`
  } else {
    return new Date(timestamp).toLocaleDateString()
  }
}

const adjustTextareaHeight = () => {
  nextTick(() => {
    if (noteTextarea.value) {
      const textarea = noteTextarea.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = `${textarea.scrollHeight + 8}px`
      }
    }
  })
}

const startEditing = () => {
  isEditing.value = true
  nextTick(() => {
    if (noteTextarea.value) {
      const textarea = noteTextarea.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.focus()
        adjustTextareaHeight()
      }
    }
  })
}

const cancelEdit = () => {
  isEditing.value = false
  noteContent.value = note.value?.content || ''
  adjustTextareaHeight()
}

const handleContainerDoubleClick = (event) => {
  const isTextareaClick = event.target.closest('.el-textarea') || 
                          event.target.classList.contains('el-textarea__inner')
  
  if (isTextareaClick) {
    return
  }
  
  if (isEditing.value) {
    isEditing.value = false
    saveNote()
  }
}

const saveNote = async () => {
  if (!noteContent.value.trim()) {
    ElMessage.warning({ message: '请输入笔记内容', duration: 350 })
    return
  }
  
  try {
    saving.value = true
    
    if (note.value?.id) {
      // 更新笔记
      await request.put(`/notes/${note.value.id}`, {
        content: noteContent.value,
        group_id: note.value.group_id
      })
      ElMessage.success({ message: '笔记更新成功', duration: 350 })
    } else {
      // 新建笔记
      const response = await request.post('/notes', {
        content: noteContent.value,
        group_id: note.value.group_id
      })
      ElMessage.success({ message: '笔记创建成功', duration: 350 })
      
      // 保存成功后返回笔记模块页面，并传递新创建的笔记数据
      const newNote = response.data.note
      router.push({
        path: '/notes',
        query: {
          newNote: JSON.stringify({
            id: newNote.id,
            content: newNote.content,
            group_id: newNote.group_id,
            group_name: newNote.group_name,
            created_at: newNote.created_at,
            updated_at: newNote.updated_at
          })
        }
      })
      return
    }
    
    isEditing.value = false
    loadNote()
  } catch (error) {
    ElMessage.error({ message: '保存笔记失败', duration: 350 })
  } finally {
    saving.value = false
  }
}

const loadNote = async () => {
  try {
    // 判断当前路由名称
    if (route.name === 'NoteNew') {
      // 新建笔记
      const groupId = route.query.group_id || null
      note.value = { id: null, content: '', group_id: groupId }
      noteContent.value = ''
      lastUpdateTime.value = ''
      adjustTextareaHeight()
      return
    }
    
    const noteId = route.params.id
    console.log('Loading note with ID:', noteId)
    
    const response = await request.get(`/notes/${noteId}`)
    note.value = response.data.note
    noteContent.value = note.value.content || ''
    
    if (note.value?.updated_at) {
      lastUpdateTime.value = formatUpdateTime(note.value.updated_at)
    } else {
      lastUpdateTime.value = ''
    }
    
    adjustTextareaHeight()
  } catch (error) {
    console.error('加载笔记失败:', error)
    ElMessage.error({ message: '加载笔记失败', duration: 350 })
    router.push('/notes')
  }
}

onMounted(() => {
  loadNote()
  
  // 每分钟更新一次时间
  const updateTime = () => {
    // 强制重新计算currentTime和currentDate
    const now = new Date()
    // 这里不需要做任何操作，computed会自动重新计算
  }
  
  // 每分钟更新一次
  const timeInterval = setInterval(updateTime, 60000)
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(timeInterval)
  })
})
</script>

<style scoped>
/* 新增：修改卡片内容区域的内边距 */
::v-deep .el-card__body {
  padding: 5px; /* 根据需要调整数值，默认通常是15px左右 */
}

/* 可选：如果需要单独调整卡片头部的内边距 */
::v-deep .el-card__header {
  padding: 8px 20px; /* 头部上下内边距16px，左右24px */
}

.note-detail-page {
  min-height: 100vh;
  background-color: var(--bg-primary);
}

.header {
  background: var(--header-bg);
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.15);
  padding: 10px 20px;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.page-title:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.title-icon {
  font-size: 24px;
  color: #ffd700;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.current-time {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 20px;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.current-time:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.time-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.time-text {
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  font-family: 'Courier New', monospace;
}

.date-text {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

.note-actions {
  display: flex;
  gap: 8px;
}

.back-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.main {
  padding: 20px;
}

.note-card {
  max-width: 800px;
  margin: 0 auto;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.note-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #52c41a;
}

.note-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.update-time {
  color: #909399;
  font-size: 12px;
}

.note-content {
  margin-bottom: 20px;
}

.note-textarea {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  height: auto !important;
  min-height: 320px;
}

.note-textarea ::v-deep .el-textarea__inner {
  min-height: 320px !important; /* 替换为你需要的最小高度（如 150px、200px） */
  overflow: hidden !important;
  resize: none !important;
}

.note-footer {
  border-top: 1px solid #e0e0e0;
  padding-top: 16px;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.note-group {
  display: flex;
  gap: 8px;
}

.note-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.edit-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.note-description {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #52c41a;
  font-size: 12px;
  font-style: italic;
}

@media (max-width: 768px) {
  html.app-5plus .header {
    padding-top: var(--status-bar-height);
    height: calc(55px + var(--status-bar-height));
  }
  
  .header-content {
    flex-direction: row;
    padding: 10px 0;
    gap: 6px;
  }
  
  .page-title {
    padding: 8px 16px;
    gap: 8px;
  }
  
  .title-icon {
    font-size: 20px;
  }
  
  .page-title h2 {
    font-size: 16px;
  }
  
  .back-btn {
    padding: 6px 10px;
    font-size: 14px;
  }
  
  .current-time {
    padding: 8px 16px;
  }
  
  .time-text {
    font-size: 16px;
  }
  
  .date-text {
    font-size: 11px;
  }
  
  .header-content .el-button span {
    display: none;
  }
  
  .main {
    padding: 10px;
  }
  
  .note-textarea {
    font-size: 13px;
    min-height: 320px; /* 设置最小高度，避免内容过少时过高 */
  }
  ::v-deep .el-textarea__inner {
      min-height: 320px !important; /* 替换为你需要的最小高度（如 150px、200px） */
    }
  
  .note-status {
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;
  }
  
  .note-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
